/**
 *  Copyright (c) 2017-2022 Rushang Co.Ltd All Rights Reserved.
 */
package com.rshang.rsdp.util.shiro;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rshang.rsdp.entity.TbUser;
import com.rshang.rsdp.service.ITbUserService;


/**
 * 功能简介：平台自定义用户认证类<br/>
 * @author zhangjun
 * @create 2017年7月28日上午11:50:48
 * 
 */
public class RsdpShiroRealm extends AuthorizingRealm {

	private static final Logger logger = LoggerFactory.getLogger(RsdpShiroRealm.class);
	
	@Autowired
	ITbUserService userService;
	
	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override//权限认证
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		//logger.debug("RsdpShiroRealm - doGetAuthorizationInfo execute!");
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		TbUser user = (TbUser)arg0.getPrimaryPrincipal();
		List<String> roles = userService.getRolesByUserId(user.getUserId());
		for(String roleName:roles){
			authorizationInfo.addRole(roleName);
		}
		List<String> auths = userService.getAuthsByUserId(user.getUserId());
		logger.debug("user:{} roles:{} auths:{}",user.getUserId(),roles,auths);
		authorizationInfo.addStringPermissions(auths);
		return authorizationInfo;
	}

	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	@Override//用户认证
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//logger.debug("RsdpShiroRealm - doGetAuthenticationInfo execute!");
//		获取用户输入账号
		String username = (String) token.getPrincipal();
		logger.debug("username:{} credentials:{}",username,token.getCredentials());
		
		EntityWrapper<TbUser> ew = new EntityWrapper<TbUser>();
		ew.setEntity(new TbUser());
		ew.where("user_name={0}", username).and("yx_bz='1'");
		
//		根据用户账号查找用户信息
		TbUser user = userService.selectOne(ew);
		logger.debug("user:{}",user);
		if(user==null)
		{
			logger.error("user not found by username:{}!",username);
			return null;
		}
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				user, //用户名
				user.getUserPass(), //密码
				user.getUserId()  //realm name
	    );
	    return authenticationInfo;
	}

}
